package com.taxiApp.util;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

public class PageHelper implements Serializable {


    private static final long 			serialVersionUID 			= 1L;

    public static final int				INFINITY = 2147483647;
    public static final PageHelper 		ONE_PAGE = new PageHelper(0,INFINITY,1);

    @Getter
    long 								recordCount; // 总行数

    @Getter @Setter
    int 								pageSize = 20; // 分页行数

    @Setter
    int 								currentPage;// 当前页码

    @Setter
    int 								pageCount;// 总页数

    @Deprecated
    @Setter
    Integer 							startIndex;

    @Getter
    String[] 							sortFields; //排序数列


    /**
     * 返回内容
     */
    @Getter	@Setter
    private List<?> contents = Collections.emptyList();


    public PageHelper() {
    }

    public PageHelper(int recordCount, int pageSize, int currentPage) {
        this.recordCount = recordCount;
        this.pageSize = pageSize;
        this.currentPage = currentPage;
    }

    public void setRecordCount(long recordCount) {
        this.recordCount = recordCount;
        check();
    }

    /**
     * 当前页
     *
     * @return
     */
    public int getCurrentPage() {
        if (currentPage <= 0) {
            currentPage = 1;
        }
        return currentPage;
    }

    /**
     * 总页数
     *
     * @return
     */
    public int getPageCount() {
        double count = (double) recordCount / pageSize;
        return (int) Math.ceil(count);
    }

    /**
     * 开始行数
     *
     * @return
     */
    public Integer getStartIndex() {
        return (getCurrentPage() - 1) * pageSize;
    }


    public void setSortFields(String... fields) {
        this.sortFields = fields;
    }

    public PageHelper check(){
        currentPage = currentPage<1 ? 1: currentPage;
        pageSize = pageSize<1 ? 20 : pageSize;
        pageCount = (int) ((recordCount+pageSize-1)/pageSize);
        currentPage = currentPage < pageCount ? currentPage : (pageCount > 0 ? pageCount : 1);
        return this;
    }

    public PageHelper paramCheck(){
        currentPage = currentPage<1 ? 1: currentPage;
        pageSize = pageSize<1 ? 20 : pageSize;
        contents = Collections.emptyList();
        return this;
    }

}
